#include <func.h>

typedef struct {
    int tickets;
    pthread_mutex_t mutex;
} data_t;

void *window1(void *p)
{
    data_t *d = (data_t *)p;
    while (1)
    {
        pthread_mutex_lock(&d->mutex);
        if (d->tickets > 0)
        {
            printf("window1 sale ticket %d\n", d->tickets --);
            pthread_mutex_unlock(&d->mutex);
        } else 
        {
            pthread_mutex_unlock(&d->mutex);
            break;
        }
        usleep(100);
    }
}

void *window2(void *p)
{
    data_t *d = (data_t *)p;
    while (1)
    {
        pthread_mutex_lock(&d->mutex);
        if (d->tickets > 0)
        {
            printf("window2 sale ticket %d\n", d->tickets);
            d->tickets --;
            pthread_mutex_unlock(&d->mutex);
        } else 
        {
            pthread_mutex_unlock(&d->mutex);
            break;
        }
        usleep(100);
    }
}

int main()
{
    pthread_t pthid[2];
    data_t d;
    d.tickets = 200;
    int ret;

    ret = pthread_mutex_init(&d.mutex, NULL);
    ERROR_CHECK(ret, -1, "pthread_mutex_init");

    ret = pthread_create(&pthid[0], NULL, window1, (void *)&d);
    ERROR_CHECK(ret, -1, "pthread_create");
    ret = pthread_create(&pthid[1], NULL, window2, (void *)&d);
    ERROR_CHECK(ret, -1, "pthread_create");
        

    ret = pthread_join(pthid[0], NULL);
    ERROR_CHECK(ret, -1, "pthread_join");
    ret = pthread_join(pthid[1], NULL);
    ERROR_CHECK(ret, -1, "pthread_join");

    ret = pthread_mutex_destroy(&d.mutex);
    ERROR_CHECK(ret, -1, "pthread_mutex_destroy");

    return 0;
}